package com.xbjtech.ticketsystem.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * @author: leejun.happy@gmail.com
 * @created: 2019年2月26日
 */
public class CaptchaUtil {
    private BufferedImage image; // 图像
    private String str; // 验证码
    private static char[] code = "ABCDEFGHJKMNPQRSTUVWXYZ23456789".toCharArray();
    public static final String SESSION_CODE_NAME = "code";

    private CaptchaUtil() {
        init(); // 初始化属性
    }

    // 取得RandomNumUtil实例
    public static CaptchaUtil Instance() {
        return new CaptchaUtil();
    }

    // 取得验证码图片
    public BufferedImage getImage() {
        return this.image;
    }

    // 取得图片的验证码
    public String getString() {
        return this.str;
    }

    private void init() {
        // 在内存中创建图象
        int width = 114, height = 42;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取图形上下文
        Graphics g = image.getGraphics();
        // 生成随机类
        Random random = new Random();
        // 设定背景色
        g.setColor(new Color(255, 157, 2));
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("sans", Font.PLAIN, 28));
        String sRand = "";
        for (int i = 0; i < 4; i++) {
            String rand = String.valueOf(code[random.nextInt(code.length)]);
            sRand += rand;
            g.setColor(Color.WHITE);
            g.drawString(rand, 18 * i + 18, 30);
        }
        this.str = sRand;
        // 图象生效
        g.dispose();
        this.image = image; // 赋值图像
    }

    public Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    public static void main(String[] args) throws FileNotFoundException {
        BufferedImage image2 = CaptchaUtil.Instance().getImage();
        OutputStream sos = new FileOutputStream("a.png");
        try {
            ImageIO.write(image2, "png", sos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            sos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}